import {useContext,useState,useEffect} from 'react'
import { PlaygroundContext } from '../../../ReactPlayground/PlaygroundContext'
import styles from './index.module.scss'
import FileNameItem from './FileNameItem'
import {ENTRY_FILE_NAME} from '../../../ReactPlayground/files'
export default function FilenameList() {
    const {files,addFile,removeFile,updateFileName,selectedFileName,setSelectedFileName} = useContext(PlaygroundContext)
const [creating,setCreating] = useState(false)
const [tabs,setTabs] = useState<string[]>([])
useEffect(()=>{
    setTabs(Object.keys(files))
},[files])
const handleEditComplete = (name:string,prevName:string) => {
    updateFileName(prevName,name)
    setSelectedFileName(name)
    setCreating(false)
}

const addTab = () => {
    const newFilename = 'Comp'+Math.random().toString().slice(2,8)+'tsx'
    addFile(newFilename)
    setSelectedFileName(newFilename)
    setCreating(true)
}
 const handleRemove = (name:string) => {
    removeFile(name)
    setSelectedFileName(ENTRY_FILE_NAME)
}
  return (
    <div className={styles['tabs']} >{
        tabs.map((tab,index,arr)=>{
            return <FileNameItem
            key={index}
            onClick={()=>setSelectedFileName(tab)}
            value={tab}
            creating={creating && index === arr.length - 1}
            actived={selectedFileName === tab}
            onEditComplete={(name:string)=>handleEditComplete(name,tab)}
            onRemove={(e:React.MouseEvent)=>{
                e.stopPropagation()
                handleRemove(tab)
            }}
            ></FileNameItem>
        })
    }
    <div className={styles['add']} onClick={addTab}>
        +
    </div>
    </div>
  )
}
